package com.bieber.smartpost.invoke;

import com.bieber.smartpost.httpcore.Response;
import com.bieber.smartpost.model.RequestEntity;
import com.bieber.smartpost.util.Utils;
import com.jbeer.framework.exception.InitializationException;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by bieber on 2014/11/6.
 */
public class BatchHttpInvoker {

    private static final Executor EXECUTOR = Executors.newCachedThreadPool();

    public static final void submitTask(HttpInvokeTask task){
        EXECUTOR.execute(new TaskRunner(task));
    }

    static class TaskRunner implements  Runnable{

        private HttpInvokeTask task;

        public TaskRunner(HttpInvokeTask task){
            this.task = task;
        }
        public void run() {
            try{
                Response lastResponse=new Response();
                FilterContext filterContext = new FilterContext();
                filterContext.setInvokeTask(task);
                filterContext.setLastResponse(lastResponse);
                for(RequestEntity entity:task.getEntities()){
                    FilterChain chain = new FilterChain(filterContext);
                    chain.doChain(entity);
                    Utils.COMMONS_LOGGER.debug(lastResponse.toString());
                }
            } catch (InitializationException e) {
                Utils.COMMONS_LOGGER.debug("failed to initialization filters ",e);
            } finally {
                CookieContainer.clearCookies(task.getInvokeId());
            }
        }
    }


}
